<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/7/30 18:42
 */

namespace App\Project\Reserve\Behaviours;

use App\Models\Patient;
use App\Models\Reservation\Reservation;
use App\User;

/**
 * 发起预约的行为
 * Class Launch
 * @package App\Project\Reserve\Behaviours
 */
class Launch
{
    protected $user;

    protected $before;

    protected $reservation;

    public function __construct(User $user)
    {
        $this->user        = $user;
        $this->reservation = new Reservation();
    }

    /**
     * @param       $patient
     * @param array $attributes
     * @return Reservation|bool
     */
    public function to($patient, array $attributes)
    {
        $patient = ($patient instanceof Patient) ? $patient->getKey() : $patient;

        if ($hasBeenCreated = $this->reservation->hasBeenCreated($patient, $attributes['time'])) {
            return $hasBeenCreated;
        }

        list($start, $end) = explode('-', $attributes['section']);
        $attributes = array_merge(
            $attributes,
            [
                'doctor_id'  => $this->user->id,
                'patient_id' => $patient,
                'status'     => 1,
                'start'      => $start,
                'end'        => $end,
            ]
        );

        return $this->reservation->create($attributes);
    }

    public function attach($patient, array $attributes)
    {
        $this->user->reservations()->attach($patient, $attributes, false);
    }
}